package externalSort;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;

public class mergeProducer implements Runnable {
    private final String inputFile;
    private final BlockingQueue<List<Integer>> bufferQueue;
    private final int bufferSize;
    private boolean isFinished = false;

    public mergeProducer(String inputFile, BlockingQueue<List<Integer>> bufferQueue, int bufferSize) {
        this.inputFile = inputFile;
        this.bufferQueue = bufferQueue;
        this.bufferSize = bufferSize;
    }

    @Override
    public void run() {
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
            List<Integer> buffer = new ArrayList<>();
            String line;

            while ((line = reader.readLine()) != null) {
                if (line.trim().isEmpty()) continue;

                buffer.add(Integer.parseInt(line.trim()));

                // 缓冲区满时发送
                if (buffer.size() >= bufferSize) {
//                    System.out.println("Producer"+inputFile+"已经向缓冲队列发送了一个buffer");
                    bufferQueue.put(new ArrayList<>(buffer));
                    buffer.clear();
                }
            }

            // 发送剩余数据
            if (!buffer.isEmpty()) {
                bufferQueue.put(new ArrayList<>(buffer));
            }

            // 发送结束信号
            bufferQueue.put(new ArrayList<>());
            isFinished = true;

        } catch (IOException | InterruptedException e) {
            System.out.println("MergeProducer错误: " + e.getMessage());
            Thread.currentThread().interrupt();
        }
    }

    public boolean isFinished() {
        return isFinished;
    }
}